#
#   __init__.py.py
#   journalismManger
#
#   Created by luoxh on 2019-07-22-17:35.
#   Copyright © 2019 luoxh. All rights reserved.
#

from mongoengine import DoesNotExist

from src.extension.exceptions import *
from src.extension.status import CustomStatus
from src.model.admin import Admin
from src.validator.common import (valid_admin_password, valid_username, )


def valid_admin_register(request):
    try:
        username = request.data['username']
        password = request.data['password']
    except KeyError: raise CustomException(CustomStatus.PARAMETER_ERROR)

    valid_admin_password(password)
    valid_username(username)

    try: Admin.objects.get(username=username)
    except DoesNotExist: pass
    else: raise CustomException(CustomStatus.USERNAME_DOES_EXIST)
    return username, password


def valid_admin_login(request):
    global admin
    try:
        username = request.data['username']
        password = request.data['password']
    except KeyError: raise CustomException(CustomStatus.PARAMETER_ERROR)
    valid_admin_password(password)
    valid_username(username)
    try: admin = Admin.objects.get(username=username)
    except DoesNotExist: raise CustomException(CustomStatus.USERNAME_DOES_NOT_EXIST)
    if not admin.check_password(password): raise CustomException(CustomStatus.PASSWORD_IS_INCORRECT)
    return admin


def valid_admin_auth(request):
    global admin
    try:
        username = request.data['username']
        password = request.data['password']
    except KeyError: raise CustomException(CustomStatus.PARAMETER_ERROR)
    valid_admin_password(password)
    valid_username(username)
    try: admin = Admin.objects.get(username=username)
    except DoesNotExist: raise CustomException(CustomStatus.USERNAME_DOES_NOT_EXIST)
    if admin.check_password(password): raise CustomException(CustomStatus.PASSWORD_IS_INCORRECT)
    return admin
